package com.icesoft.system.safe.config;

import cn.hutool.core.io.FileUtil;
import com.icesoft.framework.core.util.PathUtil;
import com.icesoft.system.safe.model.CryptoKeyPair;
import com.icesoft.system.safe.service.CryptoKeyPairRepository;
import com.icesoft.system.safe.utils.KeyPairUtils;
import com.icesoft.system.safe.utils.MD5Util;
import com.icesoft.system.safe.utils.PemFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.KeyPair;
import java.util.Base64;

@Slf4j
@Configuration
public class RsaKeyAutoCreateBean {

	private static final String DEFAULT_KEY_PATH = "key/rsaKeyPair.pem";

	public RsaKeyAutoCreateBean(CryptoKeyPairRepository cryptoKeyPairRepository) {
		KeyPair defaultKeyPair = getKey();
		CryptoKeyPair cryptoKeyPair = new CryptoKeyPair();
		String defaultKeyId = MD5Util.md5(defaultKeyPair.getPrivate().getEncoded());
		cryptoKeyPair.setPublicKey(Base64.getEncoder().encodeToString(defaultKeyPair.getPublic().getEncoded()));
		cryptoKeyPair.setPrivateKey(Base64.getEncoder().encodeToString(defaultKeyPair.getPrivate().getEncoded()));
		cryptoKeyPair.setKeyId(defaultKeyId);
		cryptoKeyPairRepository.saveKey(cryptoKeyPair);
	}

	private static KeyPair getKey() {
		String pemFilePath = PathUtil.getProjectRootPath() + DEFAULT_KEY_PATH;
		try {
			if (!FileUtil.exist(pemFilePath)) {
				return create();
			} else {
				return read();
			}
		} catch (Exception e) {
			throw new IllegalArgumentException("密钥文件读取失败：" + pemFilePath);
		}
	}

	private static KeyPair create() throws IOException {
		String pemFilePath = PathUtil.getProjectRootPath() + DEFAULT_KEY_PATH;
		KeyPair keyPair = KeyPairUtils.createKeyPair();
		PemFileUtils.writeKeyPairToFile(pemFilePath, keyPair);
		return keyPair;
	}

	private static KeyPair read() throws IOException {
		String pemFilePath = PathUtil.getProjectRootPath() + DEFAULT_KEY_PATH;
		return PemFileUtils.readKeyPair(pemFilePath);
	}


}
